import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'umi';
import { Alert, Button, Space, Tag, Modal, notification, Row, Col, Checkbox, Dropdown } from 'antd'
import { Tooltip, } from 'antd'
import { AuditOutlined, FileTextOutlined } from '@ant-design/icons'
import TableDataBlock from '@/components/TableDataBlock';
import PopImgShow from '@/components/PopImgShow';
import SearchCondition from '@/components/SearchCondition';
import SelectMateria from '@/components/MaterialModel/components/SelectModel'
import { DownOutlined } from '@ant-design/icons';
import SelectPromoterGroup from '@/components/SelectPromoterGroup';
import { goodsType_status, commission_type, categoryType_status } from '@/common/contact'
const PromoterShop = (props) => {
    const { loading, dispatch, list, zm } = props;
    const childRef = useRef();
    const [promoterGroupVisible, setPromoterVisible] = useState(false)
    const [promoterAddGroupVisible, setAddPromoterVisible] = useState(false)
    const [promoterLevelList, setPromoterLevelList] = useState([])
    const [materialVisible, setMaterialVisible] = useState(false)
    const [params, setSearchParams] = useState({})
    const [detaultShopList, setDetaultShopList] = useState([])
    const [selectedRow, setSelectedRow] = useState({
        selectedRowKeys: [],
        type: 'checked',
        preserveSelectedRowKeys: true,
        onChange: (val, selectedRows) => {
            setSelectedRow({
                ...selectedRow,
                selectedRowKeys: val,
                rowKeyList: selectedRows
            });
        },

    });
    const fetchDetault = () => {
        dispatch({
            type: 'promoter/fetchlistPromoterMaterialIdList',
            callback: (e) => {
                setDetaultShopList(e)
            }
        })
    }
    const fakeSetGroupId = (payload) => {
        dispatch({
            type: 'promoter/fakeSetMaterialGroupIds',
            payload: payload,
            callback: (e) => {
                handleCallback()
                setSelectedRow({
                    ...selectedRow,
                    selectedRowKeys: [],
                })
            }
        })
    }
    const fetchLevelList = () => {
        dispatch({
            type: 'promoter/fetchPromoterSimpleLevelDetail',
            callback: (e) => {
                const { promoterLevelList } = e
                setPromoterLevelList(promoterLevelList)
            }
        })
    }
    useEffect(() => { childRef.current.initData(); }, [params])
    useEffect(() => {
        fetchLevelList()
        fetchDetault()
    }, [])
    // 搜索参数
    const searchItems = [

        {
            label: '素材类型',
            name: 'contentType',
            type: 'select',
            select: categoryType_status
        },
        {
            label: '素材名称',
            name: 'keyword',
        },
        {
            label: '添加时间',
            type: 'rangePicker',
            name: 'createStartTime',
            end: 'createEndTime',
        },
        {
            label: '分组',
            name: 'groupId',
            type: 'promoterGroup',
        },
    ];
    function getFileExtension(fileName) {
        // 使用正则表达式匹配文件名中的后缀部分
        const regex = /(?:\.([^.]+))?$/;
        const result = regex.exec(fileName);

        // 提取匹配到的后缀，如果没有后缀则返回空字符串
        const extension = result ? result[1] : '';

        return extension;
    }
    const renderContent = (url, type, falg = true) => {
        if (type === 'image') {
            return <PopImgShow width={30} url={url}></PopImgShow>
        } else if (type === 'video') {
            return <PopImgShow width={30} url={url}></PopImgShow>
        } else if (type === 'voice') {
            return <Tooltip title={url}>
                <a style={{ fontSize: 24 }} target="_blank" href={url}><AuditOutlined></AuditOutlined></a>
            </Tooltip>
        }
        else if (type === 'ebook') {
            return <Tooltip title={url}>
                <a style={{ fontSize: 24 }} target="_blank" href={url}><FileTextOutlined></FileTextOutlined></a>
            </Tooltip>
        } else {
            const fileExtension = getFileExtension(url);
            const color = {
                pptx: '#2db7f5',
                ppt: '#87d068',
                docx: '#108ee9',
                doc: '#2db7f5',
                xls: '#87d068',
                xlsx: '#108ee9',
                pdf: '#2db7f5',
                csv: '#87d068',
                xlsm: '#2db7f5',
                txt: '#87d068',
                zip: '#2db7f5',
                vtt: '#f50'
            }[fileExtension]
            console.log(color)
            return <Tooltip title={url}><div style={{ background: color || 'red', color: '#Ffffff', width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}>{fileExtension}</div></Tooltip>
        }
    }

    // table 表头
    const getColumns = [

        {
            title: '素材名称',
            dataIndex: 'materialName',
        },
        {
            title: '素材类型',
            dataIndex: 'contentType',
            render: (e, record) => {
                return categoryType_status[e]
            },
        },

        {
            title: '素材内容',
            dataIndex: 'content',
            render: (e, record) => {
                const { contentType, cover } = record
                if (contentType === 'video') {
                    const { url } = JSON.parse(cover);
                    return renderContent(url, contentType);
                }
                const { url } = JSON.parse(e);
                return renderContent(url, contentType);
            },
        },
        {
            title: '分组',
            dataIndex: 'groupNames',
        },
        {
            title: '添加时间',
            dataIndex: 'createTime',
        },
        {
            type: 'handle',
            width: 200,
            dataIndex: 'id',
            render: (val, record) => [
                {
                    auth: true,
                    title: '设置分组',
                    click: () => {
                        const { groupIds = '' } = record
                        setPromoterVisible({
                            show: true,
                            detail: {
                                groupIds: groupIds.length ? groupIds.split(',').map(val => {
                                    return Number(val)
                                }) : []
                            },
                            selectIdList: [val]
                        })
                    },
                },
                {
                    auth: true,
                    title: record.topFlag === '1' ? '取消置顶' : '置顶',
                    click: () => {
                        dispatch({
                            type: record.topFlag === '1' ? 'promoter/fakeCancelTopPromoterMaterial' : "promoter/fakeSetTopPromoterMaterial",
                            payload: {
                                id: val
                            },
                            callback: () => {
                                handleCallback()
                            }
                        })
                    },
                },
                {
                    auth: true,
                    title: '移除',
                    click: () => {
                        Modal.error({
                            title: '确认移除素材',
                            content: `移除素材后，该组推广员将不可推广已选素材`,
                            okText: '确认',
                            onOk() {
                                dispatch({
                                    type: 'promoter/fakeRemovePromoterMaterial',
                                    payload: { id: val },
                                    callback: () => {
                                        handleCallback()
                                    }
                                })
                            },
                            onCancel() {
                                console.log('Cancel');
                            },
                        })
                    },
                },
            ],
        },
    ];
    const handleCallback = () => {
        childRef.current.fetchGetData();
    };
    const setMaterial = (e, groupIds) => {
        dispatch({
            type: 'promoter/fakeSavePromoterMaterial',
            payload: {

                promoterMaterialList: e.map(item => {
                    return {
                        materialId: item.id,
                        contentType: item.contentType,
                        groupIds,
                    }
                })
            },
            callback: () => {
                handleCallback()
            }
        })
    }

    return (

        <>
            <Row gutter={[36, 12]}>
                <Col span={24}>
                    <Space size={'large'}>
                        <Button type='primary' onClick={() => {
                            setMaterialVisible({
                                show: true
                            })
                        }}>添加素材</Button>
                    </Space>
                </Col>
                <Col span={24}>
                    <div style={{ background: '#f5f5f5', padding: 24 }}>
                        <SearchCondition
                            handleSearch={(e) => {
                                setSearchParams(e);
                            }}
                            searchItems={searchItems}
                        ></SearchCondition>
                    </div>
                </Col>
                <Col span={24}>
                    <Space>
                        <Checkbox checked={selectedRow.selectedRowKeys.length === list.list.length && list.list.length > 0} onChange={(e) => {
                            if (e.target.checked) {
                                setSelectedRow({
                                    ...selectedRow,
                                    selectedRowKeys: list.list.map(item => {
                                        return item.id.toString()
                                    }),
                                    rowKeyList: list.list
                                })
                            } else {
                                setSelectedRow({
                                    ...selectedRow,
                                    selectedRowKeys: [],
                                    rowKeyList: []
                                })
                            }

                        }}>当页全选</Checkbox>
                        <div>已选{selectedRow.selectedRowKeys.length} 条 </div>
                        <Button disabled={selectedRow.selectedRowKeys.length === 0} onClick={() => {
                            Modal.error({
                                title: '确认移除素材',
                                content: `移除素材后，该组推广员将不可推广已选素材`,
                                okText: '确认',
                                onOk() {
                                    dispatch({
                                        type: 'promoter/fakeRemovePromoterMaterial',
                                        payload: { idList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) }) },
                                        callback: () => {
                                            handleCallback()
                                            setSelectedRow({
                                                ...selectedRow,
                                                selectedRowKeys: [],

                                            })
                                        }
                                    })
                                },
                                onCancel() {
                                    console.log('Cancel');
                                },
                            })
                        }}>移除素材</Button>
                        <Button onClick={() => {
                            if (selectedRow.selectedRowKeys.length === 0) {
                                return notification.warn({
                                    message: '温馨提示',
                                    description: `请先选择要绑定的素材`,
                                });
                            } else {
                                setPromoterVisible({
                                    show: true,
                                    detail: {},
                                    type: "all",
                                    selectIdList: selectedRow.selectedRowKeys.map(item => { return parseInt(item) })
                                })
                            }
                        }}>批量绑定分组</Button>
                    </Space>
                </Col>
                <Col span={24}>
                    <TableDataBlock
                        rowSelection={selectedRow}
                        cRef={childRef}
                        loading={loading}
                        params={params}
                        firstFetch={false}
                        columns={getColumns}
                        rowKey={(record) => `${record.id}`}
                        dispatchType="promoter/fetchListPromoterMaterial"
                        {...list}
                    ></TableDataBlock>
                </Col>
                <SelectMateria getCheckboxProps={(
                    e
                ) => {
                    const flag = detaultShopList.reduce((item, val) => {
                        if (item) {
                            return item
                        }
                        return val == e.id
                    }, false)
                    return {
                        id: e.id,
                        disabled: flag

                    }
                }} onOk={(e) => setAddPromoterVisible({
                    show: true,
                    value: e
                })} title='选择素材' visible={materialVisible} onClose={() => setMaterialVisible(false)}></SelectMateria>
                <SelectPromoterGroup onChange={(e = {}) => {
                    const { selectIdList } = promoterGroupVisible
                    const { groupIds } = e
                    fakeSetGroupId({
                        idList: selectIdList,
                        groupIds: groupIds.toString()
                    })
                }} visible={promoterGroupVisible} onClose={() => setPromoterVisible(false)}></SelectPromoterGroup>
                <SelectPromoterGroup onChange={(e = {}) => {
                    const { value } = promoterAddGroupVisible
                    const { groupIds } = e
                    setMaterial(value, groupIds.toString())
                }} visible={promoterAddGroupVisible} onClose={() => setAddPromoterVisible(false)}></SelectPromoterGroup>
            </Row>
        </>
    );
};

export default connect(({ promoter, loading }) => ({
    list: promoter.promoterMaterialList,
    loading: loading.models.promoter,
}))(PromoterShop);
